import { useSessionStorage } from '@vueuse/core'
import { assign, has, isArray } from 'lodash-es'
import { Ref } from 'vue'

//课程信息本地存储
type CourseType = {
  courseBackends?: Array<Record<string, any>> | null
  documentBackends?: Array<Record<string, any>> | null
  courseEnvironment?: Array<Record<string, any>[]> | null
  documentEnvironment?: Array<Record<string, any>[]> | null
  courseId?: string
  documentId?: string
  documentIndex?: number
  title?: string
  duration?: number
  termiate?: number
  stepIndex: number
}

//课程信息本地存储
export const useCourse = () => {
  const course: Ref<CourseType> = useSessionStorage('course', {
    courseBackends: null,
    documentBackends: null,
    courseEnvironment: null,
    documentEnvironment: null,
    courseId: '',
    documentId: '',
    documentIndex: -1,
    title: '',
    duration: 7200,
    termiate: 1036800,
    stepIndex: -1,
  })

  const setCourse = (info: CourseType) => {
    console.log(info);
    
    if (has(info, 'courseEnvironment')) {
      if (!isArray(info.courseEnvironment) && info.courseEnvironment) {
        info.courseEnvironment = [[info.courseEnvironment]]
      }
    }
    if (has(info, 'documentEnvironment')) {
      if (!isArray(info.documentEnvironment) && info.documentEnvironment) {
        info.documentEnvironment = [[info.documentEnvironment]]
      }
    }
    assign(course.value, info)
  }
  return { course, setCourse }
}
